import React from 'react';
import {
    View,
    Text,
    FlatList,
    TouchableOpacity,
    Dimensions,
    Image,
} from 'react-native';
import NavigationBar from '../../common/NavigationBar';
import {BASE_URL} from '../../common/BASE_URL';
import HttpUtils from '../../expand/dao/HttpUtils';
import {Constant, StylesConstant} from '../../common/Constant';
import StorageUtil from '../../utils/StorageUtil';
import NavigationUtil from '../../navigators/NavigationUtil';
import Utils from '../../utils/Utils';
import GlobalStyles from '../../common/styles/GlobalStyles';
import {Tabs} from '@ant-design/react-native';
import ChooseReportType from './components/ChooseReportType'
import AddPersonalInfoForm from './components/AddPersonalInfoForm'
import PersonalInfoForm from "./components/PersonalInfoForm";
import CaseInfoForm from "./components/CaseInfoForm";
import ToastUtil from '../../utils/ToastUtil';
import styles from './styles'
import CaseDocument from "./components/CaseDocument";
import DealWay from "./components/DealWay";

const saveCaseReportUrl =  BASE_URL.apiBaseUrl + '/api/caseInfo'
const saveCaseRecordsUrl =  BASE_URL.apiBaseUrl + '/api/inspectionRecords'

// 查询巡查待办详情
const queryInspectionByCode = BASE_URL.apiBaseUrl + '/app/inspectionRecords/findViewByCaseCode'
const queryCaseByCode = BASE_URL.apiBaseUrl + '/app/viewCaseInfo/findByCaseCode'

export default class CaseReport extends React.Component {
    constructor(props) {
        super(props);
        // 获取参数
        let tabIndex = 0;
        this.state = {
            reportType: '',
            tabIndex: tabIndex,
            isLoading: true, // list加载状态
            // 个人信息
            caseLitigants: [],
            // 案件信息
            caseInfo: {},
            // 文书表单
            documentInfo: {},
            // 文书
            caseTextData: []
        };
    }

    componentDidMount() {
        // this.loadData();
        const {type, caseCode, matterId, linkId} = this.props.navigation.state.params;
        // 全局缓存
        this.type = type
        this.matterId = matterId
        this.linkId = linkId;
        this.caseCode = caseCode
        if(type && caseCode){
            console.log('编辑： ',caseCode);
            let queryUrl = queryCaseByCode;
            if(type === 'caseInfo'){
                queryUrl = queryCaseByCode;
            }else if(type === 'inspection'){
                queryUrl = queryInspectionByCode;
            }
            const key = ToastUtil.loading('加载中')
            HttpUtils.request({
                url: queryUrl,
                params: {
                    caseCode
                }
            }).then(res=>{
                ToastUtil.remove(key)
                // console.log('update: ',res);
                if(res && !res.status){
                    let counterpartTypeStr = "";
                    if(res.counterpartType === 0){
                        counterpartTypeStr = "personal";
                    }else if(res.counterpartType === 1){
                        counterpartTypeStr = "company";
                    }
                    this.setState({
                        reportType: counterpartTypeStr,
                        caseLitigants: res.caseLitigants,
                        caseInfo: res
                    })
                    const {dept} = res
                    let deptId = '', deptName = ''
                    if(dept){
                        deptId = dept.id
                        deptName = dept.name
                    }

                    this.refs.caseLitigants && this.refs.caseLitigants.setData(res.caseLitigants)
                    this.refs.caseInfoForm && this.refs.caseInfoForm.setCaseInfo({
                        ...res,
                        undertakerName: res.undertakerOfficer?res.undertakerOfficer.name: '',
                        undertaker2Name: res.undertakerOfficer2?res.undertakerOfficer2.name: '',
                        undertakerDept: deptId,
                        undertakerDeptLabel : deptName,
                        caseTimeStr: res.caseTime? new Date(res.caseTime).Format('yyyy-MM-dd hh:mm:ss'): '',
                        inspectionEndTimeStr: res.inspectionEndTime? new Date(res.inspectionEndTime).Format('yyyy-MM-dd hh:mm:ss'): '',

                    })
                }
            }).catch(()=>{
                ToastUtil.remove(key)
            })
        }

    }

    loadData() {
        const {tabIndex} = this.state;
        this.setState({
            isLoading: false,
        })
    }
    _handleChooseReportType(type){
        this.setState({
            reportType: type
        })
    }
    render() {
        const {navigation} = this.props;
        const {tabIndex,reportType} = this.state;
        return (
            <View style={GlobalStyles.pageContainer}>
                {/* 自定义顶部导航条 */}
                <NavigationBar
                    navigation={navigation}
                    headerBackTitle={'案事件详情'}
                />
                <View style={{flex: 1}}>
                    {reportType?
                        this._renderTabs():
                        <ChooseReportType chooseType={(item)=>this._handleChooseReportType(item)}/>
                    }
                </View>
            </View>
        );
    }
    formDataChange(key,value){
        // console.log(key,value)
        this.setState({
            [key]: value
        })
    }

    _renderTabs(){
        const {tabIndex,reportType} = this.state;
        const reportTypeStr = reportType==='personal'?'个人':reportType==='company'?'单位':reportType==='event'?'提供人':'个人'
        return (
            <>
                <Tabs
                    style={[styles.container, GlobalStyles.bgGrey]}
                    initialPage={tabIndex}
                    tabBarTextStyle={GlobalStyles.tabsTextStyle}
                    tabBarUnderlineStyle={GlobalStyles.tabsLineStyle}
                    tabBarActiveTextColor={GlobalStyles.tabBarActiveTextColor}
                    tabBarInactiveTextColor={GlobalStyles.tabBarInactiveTextColor}
                    onChange={(tab, index) => this.handleTabChange(tab, index)}
                    tabs={[
                        {title: reportTypeStr},
                        {title: '案件信息'},
                        // {title: '证据材料'},
                        // {title: '视频存证'},
                        {title: '处理方式'},
                        {title: '案件文书'},
                    ]}>
                    {reportType === 'personal'?
                    <View tabLabel="个人" style={{flex: 1}}>
                        <AddPersonalInfoForm type={this.type} ref={'caseLitigants'} caseLitigant={this.state.caseLitigants}
                                             onChange={(data)=>this.formDataChange('caseLitigants',data)}/>
                        {/*<PersonalInfoForm onChange={(data)=>this.formDataChange('caseLitigants', data)}/>*/}
                    </View> : reportType === 'company'?
                    <View tabLabel="单位" style={{flex: 1}}>
                        <AddPersonalInfoForm type={this.type} ref={'caseLitigants'} caseLitigant={this.state.caseLitigants}
                                             onChange={(data)=>this.formDataChange('caseLitigants',data)}/>
                        {/*<PersonalInfoForm onChange={(data)=>this.formDataChange('caseLitigants', data)}/>*/}
                    </View> : reportType === 'event'?
                    <View tabLabel="提供人" style={{flex: 1}}>
                        <AddPersonalInfoForm type={this.type} ref={'caseLitigants'} caseLitigant={this.state.caseLitigants}
                                             onChange={(data)=>this.formDataChange('caseLitigants',data)}/>
                        {/*<PersonalInfoForm onChange={(data)=>this.formDataChange('caseLitigants', data)}/>*/}
                    </View> :
                    <View tabLabel="个人" style={{flex: 1}}>
                        <AddPersonalInfoForm type={this.type} ref={'caseLitigants'} caseLitigant={this.state.caseLitigants}
                                             onChange={(data)=>this.formDataChange('caseLitigants',data)}/>
                        {/*<PersonalInfoForm onChange={(data)=>this.formDataChange('caseLitigants', data)}/>*/}
                    </View>
                    }
                    <View tabLabel="案件信息" style={{flex: 1}}>
                        <CaseInfoForm type={this.type} ref={'caseInfoForm'} caseInfo={this.state.caseInfo}
                                      onChange={(data)=>this.formDataChange('caseInfo', data)}/>
                    </View>
                    {/*<View tabLabel="证据材料" style={{flex: 1}}><Text>1</Text></View>*/}
                    {/*<View tabLabel="视频存证" style={{flex: 1}}><Text>1</Text></View>*/}
                    <View tabLabel="处理方式" style={{flex: 1}}>
                        <DealWay type={this.type} linkId={this.linkId} caseCode={this.caseCode}
                                 onChange={(data)=>this.formDataChange('documentInfo',data)}/>
                    </View>
                    <View tabLabel="案件文书" style={{flex: 1}}>
                        <CaseDocument
                            documentInfo={this.state.documentInfo}
                            caseTextData={this.state.caseTextData}
                            onChange={(data)=>this.formDataChange('caseTextData',data)}
                        />
                    </View>
                </Tabs>
                {this._renderBottomBtns()}
            </>
        )
    }

    _renderBottomBtns(){
        const {type} = this.props
        return (
            <View style={styles.bottomBtnsPanel}>
                <TouchableOpacity
                    style={styles.saveBtn}
                >
                    <Text style={styles.saveBtnText}>暂存</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.submitBtn}
                    onPress={()=>this._handleSave()}
                >
                    <Text style={styles.submitBtnText}>提交</Text>
                </TouchableOpacity>
            </View>
        )
    }
    _handleSave(){
        const {caseInfo,caseLitigants,documentInfo,caseTextData} = this.state
        let submitData = {
            counterpartType: 0,
            ...caseInfo,
            caseLitigants: caseLitigants,
            ...documentInfo,
            casePendingMatters:[],
        }

        // if(submitData.inspectionPendingMatter && submitData.inspectionPendingMatter.additionalOperations) {
        //     submitData.additionalOperations = submitData.inspectionPendingMatter.additionalOperations
        // }
        if(submitData.casePendingMatter && submitData.casePendingMatter.additionalOperations) {
            submitData.additionalOperations = submitData.casePendingMatter.additionalOperations
        }
        if(submitData.casePendingMatter && submitData.casePendingMatter.nextHandlerOfficerIds){
            submitData.casePendingMatter.officers = submitData.casePendingMatter.nextHandlerOfficerIds.map(
                item => {
                    return { officerId: parseInt(item) };
                }
            );
        }
        if(submitData.inspectionPendingMatter && submitData.inspectionPendingMatter.nextHandlerOfficerIds){
            submitData.inspectionPendingMatter.officers = submitData.inspectionPendingMatter.nextHandlerOfficerIds.map(
                item => {
                    return { officerId: parseInt(item) };
                }
            );
        }
        if(this.type === 'inspection'){
            submitData.inspectionPendingMatter.officers = submitData.casePendingMatter.officers
        }
        // inspectionActionRecord
        if(submitData.inspectionPendingMatter){
            submitData.inspectionPendingMatter.inspectionActionRecord = submitData.inspectionPendingMatter.caseActionRecord
            // submitData.inspectionPendingMatter.caseActionRecord = null
        }
        let saveUrl = saveCaseReportUrl
        if(this.type === 'caseInfo'){
            saveUrl = saveCaseReportUrl
            submitData.casePendingMatter.id = this.matterId
        }else if(this.type === 'inspection'){ // 修改
            saveUrl = saveCaseRecordsUrl
            submitData.inspectionPendingMatter.id = this.matterId
        }else{
            // 新增
            if(documentInfo && documentInfo.casePendingMatter && documentInfo.casePendingMatter.linkHandleName){
                submitData.inspectionPendingMatter = null
            } else {
                saveUrl = saveCaseRecordsUrl
            }
        }
        submitData.casePendingMatters.push(submitData.casePendingMatter)
        // 文书列表替换
        let items = [];
        let inspectionText = {};

        for (let j = 0, len = caseTextData.length; j < len; j++) {
            const item = caseTextData[j];
            if (item.type === "XCWS") {
                // 巡查文书
                inspectionText = item;
            } else {
                items.push(item);
            }
        }
        submitData.caseTexts = items;
        submitData.inspectionText = inspectionText;

        // return;
        console.log('submit: ',submitData)
        const key = ToastUtil.loading('保存中...')
        HttpUtils.request({
            url: saveUrl,
            type: this.type?'put':'post',
            data: submitData
        }).then(res=>{
            ToastUtil.remove(key)
            console.log(res);
            if(res && !res.status){
                ToastUtil.info('提交成功')
                NavigationUtil.goPage('IndexPage')
            }else if(res){
                ToastUtil.info(res.message)
                NavigationUtil.goPage('IndexPage')
            }else{
                ToastUtil.info(res.message)
            }
        }).catch((e)=>{
            console.log(e);
            ToastUtil.remove(key)
        })
        // const key = ToastUtil.loading('保存中...')
        // setTimeout(()=>{
        //     ToastUtil.remove(key)
        //     ToastUtil.info('保存成功')
        //     NavigationUtil.goPage('IndexPage')
        // }, 2000)
    }
    handleTabChange(obj, index) {
        if (this.state.index !== index) {
            this.state.tabIndex = index;
        }
    }

}
